<template>
  <div class="app-container">
    <el-form class="formBox searchForm" :model="queryParams" ref="queryParams" size="small" :inline="true"
      v-show="showSearch" label-width="68px">
      <el-form-item clearable label="医院" prop="hospital">
        <department ref="department" :isHospital="true" :isdepat="true" deptWidth="200px" @refreshData="refreshData">
        </department>
      </el-form-item>
      <el-form-item label="顾客ID" prop="patientId">
        <el-input v-model="queryParams.patientId" placeholder="顾客ID" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="顾客编号" prop="visitNum">
        <el-input v-model="queryParams.visitNum" placeholder="请输入顾客编号" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入顾客姓名" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNum">
        <el-input v-model="queryParams.idNum" placeholder="顾客身份证号" clearable style="width: 185px" @focus="getSFZToSearch"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" filterable placeholder="请选择诊断状态" clearable style="width: 160px">-->
      <!--          <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value" :label="dict.label"-->
      <!--            :value="dict.value" />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="就诊门诊" prop="status">-->
      <!--        <treeselect v-model="baseInfo.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择就诊门诊"-->
      <!--          style="width: 202px" />-->
      <!--      </el-form-item>-->
      <el-form-item label="诊断医生" prop="createBy">
        <el-select v-model="queryParams.createBy" @change="handleQuery" :disabled="isDisabled" filterable
          placeholder="请选择医生" clearable style="width: 160px">
          <el-option v-for="(item, index) in doctorList" :key="index" :label="item.nickName"
            :value="item.userName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="formBox searchForm" style="margin-bottom:0px!important;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" :plain="waitDiagnosisBtn ? false : true" icon="el-icon-circle-plus-outline"
            size="mini" @click="waitDiagnosis">待诊断</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" :plain="haveDiagnosisBtn ? false : true" icon="el-icon-circle-check" size="mini"
            @click="haveDiagnosis">我的录入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" :plain="haveDiagnosisBtnInfo ? false : true" icon="el-icon-circle-check" size="mini"
            @click="haveDiagnosisInfo">我已诊断</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery"></right-toolbar>
      </el-row>
      <el-row v-show="haveDiagnosisBtn">
        <div class="formBox searchForm">
          <el-form :inline="true">
            <el-form-item label="咨询日期">
              <el-date-picker v-model="myDiagnosisDateRange" style="width: 380px" value-format="yyyy-MM-dd"
                type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="myDiagnosisTabSearch" style="margin-left:15px;">搜索</el-button>
              <el-button type="primary" plain size="mini" @click="getMyDiagnosisList(true)"
                style="margin-left:15px;">汇总统计</el-button>
            </el-form-item>
          </el-form>
          <div class="statisticalBox">
            <span><strong>{{ statisticalBeginTime }} -- {{ statisticalEndTime }}</strong>，</span>
            <span>共诊断 <strong>{{ statisticalCount }}</strong> 人，</span>
            <span>诊断方案总费用 <strong>{{ statisticalTotalExpenses }}</strong> 元，其中治疗费
              <strong>{{ statisticalTreatmentExpenses }}</strong> 元。</span>
          </div>

        </div>

      </el-row>
      <el-row v-show="haveDiagnosisBtnInfo">
        <div class="formBox searchForm">
          <el-form :inline="true">
            <el-form-item label="咨询日期">
              <el-date-picker v-model="myDiagnosisDateRange" style="width: 380px" value-format="yyyy-MM-dd"
                type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="myDiagnosisTabSearchInfo"
                style="margin-left:15px;">搜索</el-button>
              <el-button type="primary" plain size="mini" @click="getMyDiagnosisListInfo(true)"
                style="margin-left:15px;">汇总统计</el-button>
            </el-form-item>
          </el-form>
          <div class="statisticalBox">
            <span><strong>{{ statisticalBeginTime }} -- {{ statisticalEndTime }}</strong>，</span>
            <span>共诊断 <strong>{{ statisticalCount }}</strong> 人，</span>
            <span>诊断方案总费用 <strong>{{ statisticalTotalExpenses }}</strong> 元，其中治疗费
              <strong>{{ statisticalTreatmentExpenses }}</strong> 元。</span>
          </div>

        </div>

      </el-row>
      <div ref="statisticalTable">
        <el-table border v-loading="loading" style="width: 100%" :data="patientList" :height="statisticalTableH"
          ref="table">
          <el-table-column label="序号" align="center" type="index" width="50">
            <template slot-scope="scope">
              <span>{{ getIndex(scope.$index) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="顾客ID" align="center" prop="patientId" :show-overflow-tooltip="true"
            width="100" />
          <el-table-column sortable label="顾客编号" align="center" prop="visitNum" width="160">
            <template slot-scope="scope">
              <el-tooltip placement="right" effect="light">
                <div slot="content" v-html="renderTooltip(scope.row)" style="max-width: 700px" />
                <span style="text-decoration: underline;color: #10a1df; ">
                  {{ scope.row.visitNum }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column sortable label="顾客姓名" align="center" prop="patientName" :show-overflow-tooltip="true"
            width="100" />
          <el-table-column sortable label="性别" align="center" prop="sex" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <el-table-column sortable label="年龄" align="center" prop="age" width="80">
          </el-table-column>

          <el-table-column sortable label="状态" align="center" prop="status" :show-overflow-tooltip="true" width="120">
            <!--          <template slot-scope="scope">-->
            <!--            <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />-->
            <!--          </template>-->
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == '0'" type="danger" size="mini">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '1'" type="warning" size="mini">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '3'" type="success" size="mini">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '4'" size="mini">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column sortable label="照片" align="center" prop="photoCount">
            <template slot-scope="scope">
              <el-tag size="mini" :type="parseInt(scope.row.photoCount) > 0 ? 'primary' : 'danger'">{{
                scope.row.photoCount }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable label="咨询诊断" align="left" prop="consultationDiagnosisValue" width="220">
            <template slot-scope="scope">
              <span v-html="scope.row.consultationDiagnosisValue"></span>
            </template>
          </el-table-column>
          <el-table-column sortable label="咨询方案" align="left" prop="consultationPlan" width="220">
            <template slot-scope="scope">
              <el-tooltip placement="top" effect="light">
                <div slot="content" v-html="scope.row.consultationPlan" style="max-width: 700px;font-size:18px;"></div>
                <div v-html="scope.row.consultationPlan"
                  style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"></div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column sortable label="咨询医生" align="center" prop="consultationer" width="100" />
          <el-table-column sortable label="咨询日期" align="center" prop="consultationTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.consultationTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="医生诊断" align="left" prop="doctorDiagnosisValue" width="220">
            <template slot-scope="scope">
              <span v-html="scope.row.doctorDiagnosisValue"></span>
            </template>
          </el-table-column>
          <el-table-column label="医生方案" align="left" prop="doctorPlan" width="220">
            <template slot-scope="scope">
              <el-tooltip placement="top" effect="light">
                <div slot="content" v-html="scope.row.doctorPlan" style="max-width: 700px;font-size:18px;"></div>
                <div v-html="scope.row.doctorPlan" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column sortable label="诊断医生" align="center" prop="doctor" width="100" />
          <el-table-column sortable label="诊断日期" align="center" prop="doctorTime" width="180">
            <template slot-scope="scope">

              <span>{{ parseTime(scope.row.doctorTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="通用问卷" align="center" prop="questionnaireStatus" width="100px">
            <template slot-scope="scope">
              <el-tag :type="scope.row.questionnaireStatus == '1' ? 'danger' : 'primary'" size="mini">
                <dict-tag :options="dict.type.sys_general_questionnaire" :value="scope.row.questionnaireStatus" />
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable label="专病问卷" align="center" prop="diseaseQuestionnaireStatus" width="100px">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.diseaseQuestionnaireStatus == '0' ? 'danger' : 'primary'">
                {{ scope.row.diseaseQuestionnaireStatus == '0' ? '未填写' : scope.row.diseaseQuestionnaireStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable label="就诊门诊" align="center" prop="deptName" :show-overflow-tooltip="true"
            width="108" />


          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="260">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-document" @click="openQuestionnaireUniversal(scope.row)"
                v-if="scope.row.questionnaireStatus == '1'" :disabled="Number(scope.row.status) >= 3"
                v-hasPermi="['doctorWorkstation:diagnosisList:generalQuestionnaire']">诊前问卷</el-button>
              <el-button size="mini" type="text" icon="el-icon-document" @click="updateQuestionnaireUniversal(scope.row)"
                v-else :disabled="Number(scope.row.status) >= 3"
                v-hasPermi="['doctorWorkstation:diagnosisList:generalQuestionnaire']">修改通用问卷</el-button>
              <el-button size="mini" type="text" icon="el-icon-document" @click="openQuestionnaire(scope.row)"
                v-if="scope.row.diseaseQuestionnaireStatus == '0'" :disabled="Number(scope.row.status) >= 3"
                v-hasPermi="['doctorWorkstation:diagnosisList:diseaseQuestionnaire']">专病问卷</el-button>
              <el-button size="mini" type="text" icon="el-icon-document" @click="updateQuestionnaire(scope.row)" v-else
                :disabled="Number(scope.row.status) >= 3"
                v-hasPermi="['doctorWorkstation:diagnosisList:diseaseQuestionnaire']">修改专病问卷</el-button>
              <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="newAdd(scope.row)"
                v-if="!(scope.row.doctor)" v-hasPermi="['doctorWorkstation:diagnosisList:add']">新增方案</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="updatePlan(scope.row)" v-else
                v-hasPermi="['doctorWorkstation:diagnosisList:add']">修改方案</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="referencePlan(scope.row)"
                v-if="!(scope.row.doctor)" :disabled="!(scope.row.visitPlanId)"
                v-hasPermi="['doctorWorkstation:diagnosisList:reference']">引用咨询方案</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="referencePlan(scope.row)" v-else
                :disabled="!(scope.row.visitPlanId)"
                v-hasPermi="['doctorWorkstation:diagnosisList:reference']">查看咨询方案</el-button>
              <el-button size="mini" type="text" icon="el-icon-user" @click="goDetail(scope.row)"
                v-hasPermi="['doctorWorkstation:diagnosisList:detail']">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="(waitDiagnosisBtn == true) && (total > 0)" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getWaitDiagnosisList" />
        <pagination v-show="(haveDiagnosisBtn == true) && (total > 0)" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getDiagnosisDetailList" />
        <pagination v-show="(haveDiagnosisBtnInfo == true) && (total > 0)" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getDiagnosisDetailListInfo" />
        <pagination
          v-show="(waitDiagnosisBtn == false) && (haveDiagnosisBtn == false) && (haveDiagnosisBtnInfo == false) && (total > 0)"
          :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getPatientList" />
      </div>
    </div>
    <!-- 通用问卷 -->
    <el-dialog :title="questionnaireTitleUniversal" :visible.sync="questionnaireDialogUniversal" width="1000px"
      :close-on-click-modal="false" v-dialogDrag>
      <formpreview v-if="formpreviewContListUniversal != null" :formPreviewList="formpreviewContListUniversal"
        ref="formPreviewUniversal" :questionFormInfo="questionFormInfoUniversal" />
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogNewAddBtnStatusUniversal === true" @click="submitAnswerUniversal">提 交</el-button>
        <el-button v-else @click="updateFormAnswerUniversal">修 改</el-button>
        <el-button @click="questionnaireDialogUniversal = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 专病问卷 -->
    <el-dialog :title="questionnaireTitle" :visible.sync="questionnaireDialog" width="1000px" v-dialogDrag
      :close-on-click-modal="false">
      <el-row>
        适用专病：
        <el-select v-model="selectData.diseaseId" filterable placeholder="专病名称" style="width: 240px" @change="getFormList"
          :disabled="!dialogNewAddBtnStatus">
          <el-option v-for="dict in classifyList" :key="dict.diseaseClassifyId" :label="dict.diseaseClassifyName"
            :value="dict.diseaseClassifyId"></el-option>
        </el-select>
        专病问卷：<el-select v-model="selectData.formId" filterable placeholder="请选择专病诊前问卷表" style="width: 440px"
          @change="getFormContByFormId">
          <el-option v-for="item in formList" :key="item.formId" :label="item.formName" :value="item.formId"></el-option>
        </el-select>
        <el-button v-if="dialogNewAddBtnStatus === false" @click="addQuestionForm" type="primary"
          style="margin-left:15px">添加新问卷</el-button>
      </el-row>
      <el-row class="base-info-box">
        <span>身份证: {{ formInfo.idNum }} </span>
        <span>顾客编号: {{ formInfo.visitNum }} </span>
        <span>姓名: {{ formInfo.patientName }} </span>
        <span>性别:
          <dict-tag :options="dict.type.sys_user_sex" :value="formInfo.sex" style="display: inline-block" /></span>
        <span>状态:
          <dict-tag :options="dict.type.sys_diagnosis_status" :value="formInfo.status" style="display: inline-block" />
        </span>
      </el-row>
      <div class="min-height">
        <formpreview v-if="formpreviewContList != null" :formPreviewList="formpreviewContList" ref="formPreview"
          :questionFormInfo="questionFormInfo" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogNewAddBtnStatus === true" @click="submitAnswer" type="primary"
          :disabled="!selectData.formId">提 交</el-button>
        <el-button v-else @click="updateFormAnswer" type="primary">修 改</el-button>
        <el-button @click="questionnaireDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增或者修改方案 -->
    <el-dialog :title="planTitle" :visible.sync="centerDialogVisible" width="100%" center @close="closefullScreen"
      v-dialogDrag>
      <diagnosisListDetail v-if="centerDialogVisible" :baseInfo="baseInfo"
        @closeCenterDialogVisible="closeCenterDialogVisible">
      </diagnosisListDetail>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog :title="detailTitle" :visible.sync="detailDialogVisible" :width="device !== 'mobile' ? '85%' : '100%'"
      class="nopaddingDailog" :class="device !== 'mobile' ? '' : 'active'" v-dialogDrag :close-on-click-modal="false">
      <CustomerDetails v-if="detailDialogVisible" :basicInfo="baseInfo"></CustomerDetails>
    </el-dialog>
    <!-- 汇总统计 -->
    <el-dialog :title="statisticalTitle" :visible.sync="statisticalDialogVisible" width="80%" append-to-body v-dialogDrag>
      <div class="formBox">
        <el-table border style="width: 100%" :data="myDiagnosisTabList">
          <el-table-column sortable label="日期" align="center" prop="consultationDate" width="120" />
          <el-table-column sortable label="星期" align="center" prop="weekday" width="120" />
          <el-table-column sortable label="诊断医生" align="center" prop="doctor" width="120" />
          <el-table-column sortable label="诊断人次数" align="center" prop="coun" width="120" />
          <el-table-column sortable label="咨询方案总费用" align="center" prop="consultationTotalExpenses" />
          <el-table-column sortable label="其中总治疗费" align="center" prop="consultationTreatmentExpenses" />
          <el-table-column sortable label="医生方案总费用" align="center" prop="doctorTotalExpenses" />
          <el-table-column sortable label="其中总治疗费" align="center" prop="doctorTreatmentExpenses" />
        </el-table>
        <pagination v-show="myDiagnosisTabTotal > 0" :total="myDiagnosisTabTotal"
          :page.sync="myDiagnosisQueryParams.pageNum" :limit.sync="myDiagnosisQueryParams.pageSize"
          @pagination="getMyDiagnosisList(true)" />
      </div>

    </el-dialog>

    <Screenfull v-show="false" ref="Screenfull"></Screenfull>
  </div>
</template>

<script>
import department from "@/views/components/department/index.vue";
import { mapGetters } from "vuex";
import { addressJson } from "@/api/patients/personal";
import { deptTreeSelect, getListUser, listUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  diagnosisDetail,
  diagnosisWait,
  getDropdownList,
  getList,
  myDiagnosis,
  diagnosisDetailInfo,
  myDiagnosisInfo,
} from "@/api/doctorWorkstation/diagnosisList";
import diagnosisListDetail from "@/views/components/customerDetail/diagnosisListDetail";
import Formpreview from "@/views/system/form/Formpreview";
import CustomerDetails from '@/views/components/customerDetail/customerDetail'
import { diseaseQuestionnaireList } from "@/api/consultation/consultation";
import {
  addFormAnswer,
  listForm,
  listFormCont,
  updateAnswer,
  currencyFormId,
  detailFormAndAnswer,
  listFormDept
} from "@/api/system/form";
import { getQuestionnaireCommon, } from "@/api/patientRegistration/registrationList";
import { listClassify } from "@/api/system/classify";
import { startReadCard } from "@/utils/getIdCard"
import Screenfull from "@/components/Screenfull";
import { listDept } from "@/api/system/dept";
export default {
  name: "Registration",
  dicts: ["sys_diagnosis_status", "sys_user_sex", "sys_patient_properties", "sys_skin_tone", "sys_patient_sort", "sys_outpatient_clinic", "sys_general_questionnaire", "sys_patient_reason"],
  components: { Formpreview, Treeselect, diagnosisListDetail, CustomerDetails, Screenfull, department },
  data() {
    return {
      statisticalTableH: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      patientNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 登记顾客列表
      patientList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined, // deptId: 0,
        hospitalId: undefined,
        patientId: '',
        createBy: '',
        status: '',
        patientName: '',
        visitNum: '',
        idNum: '',
      },

      // 科室树选项
      deptOptions: undefined,
      // 科室名称
      deptName: undefined,

      // 省市区
      areaList: [],
      //专属医生列表
      doctorList: [],
      userName: this.$store.state.user.name,
      isDisabled: false,
      centerDialogVisible: false,
      planTitle: '',
      baseInfo: { updateStatus: false, },
      // jumpCurrentTab:'projectManagement',
      detailTitle: '',
      detailDialogVisible: false,

      myDiagnosisTabList: [],
      myDiagnosisTabTotal: 0,
      myDiagnosisQueryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined, // deptId: 0,
        hospitalId: undefined,
      },
      myDiagnosisDateRange: [],

      waitDiagnosisBtn: false,
      haveDiagnosisBtn: false,
      haveDiagnosisBtnInfo: false,
      statisticalTitle: '',
      statisticalDialogVisible: false,
      statisticalBeginTime: '',
      statisticalEndTime: '',
      statisticalCount: '',
      statisticalTotalExpenses: '',
      statisticalTreatmentExpenses: '',
      questionnaireTitle: "", // 诊前问卷弹出层标题
      questionnaireDialog: false, // 诊前问卷弹出层是否显示
      dialogNewAddBtnStatus: false, //诊前问卷弹窗新增或者修改状态
      formList: [], //表单列表
      selectData: { formId: null, diseaseId: null }, //选中的表单
      formInfo: {}, //记录点击的这行里的所有字段
      questionFormInfo: {
        name: "",
        remark: "",
      }, //选中的表单名称和说明
      formpreviewContList: null, //存放表单和答案列表
      myAnswer: null, //存放表单答案
      classifyList: [],



      //通用问卷start
      formpreviewContListUniversal: null,
      formInfoUniversal: {},
      questionFormInfoUniversal: {
        name: "",
        remark: "",
      },
      dialogNewAddBtnStatusUniversal: "",
      myAnswerUniversal: null,
      questionnaireTitleUniversal: "",
      questionnaireDialogUniversal: false,
      //通用问卷end

    };
  },
  computed: {
    ...mapGetters(["dept", "hospital", "device"]),
    defaultTime: function () {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = (month > 9) ? month : ("0" + month);
      day = (day < 10) ? ("0" + day) : day;
      let today = year + "-" + month + "-" + day
      return [today, today]
    }
  },
  watch: {
    // 根据名称筛选科室树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    showSearch() {
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)

    }
  },
  created() {
    // this.getPatientList()

  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  mounted() {
    this.changeHeight()
  },
  methods: {
    changeHeight() {
      if (this.$refs.statisticalTable) {
        const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
        let h = statisticalTableObj.top + 62
        this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
      } else {
        this.statisticalTableH = '500px'
      }
    },
    refreshData(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.hospitalId = data.hospitalId;
      this.queryParams.deptId = data.deptId;
      this.myDiagnosisQueryParams.hospitalId = data.hospitalId;
      this.myDiagnosisQueryParams.deptId = data.deptId;

      this.getClassifyList();
      this.waitDiagnosis()
      this.getAddressData();
      this.getDeptTree();
      this.getDoctorList()
    },
    renderTooltip(row) {
      return `<div style="margin-bottom:5px;font-size:20px;color:#1890ff;"><span style="font-weight:bold;"> 顾客状态：</span>${this.matchDict("sys_diagnosis_status", row.status)}</div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">登记日期：</span>${this.parseTime(row.createTime)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">登记人：</span>${this.formatValue(row.createBy)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">就诊科室：</span>${this.formatValue(row.deptName)}</span> </div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">顾客性质：</span>${this.matchDict("sys_patient_properties", row.properties)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">顾客分类：</span>${this.matchDict("sys_patient_sort", row.customerSort)}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">地址：</span>${this.formatValue(row.address)}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">电话：</span>${this.formatValue(row.patientPhone)}</div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">通用问卷：</span>${this.matchDict("sys_general_questionnaire", row.questionnaireStatus)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">专病问卷：</span>${this.formatValue(row.diseaseQuestionnaireStatus)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">照片：</span>${this.formatValue(row.photoCount)}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">咨询日期：</span>${this.formatValue(row.consultationTime)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">咨询医生：</span>${this.formatValue(row.consultationer)}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">咨询诊断：</span>${this.formatValue(row.consultationDiagnosis)}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">咨询方案：</span>${this.formatValue(row.consultationPlan)}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">方案总额：</span>${this.formatValue(row.consultationTotalExpenses)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗费用：</span>${this.formatValue(row.consultationTreatmentExpenses)}</span></div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">诊断日期：</span>${this.formatValue(row.doctorTime)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">诊断医生：</span>${this.formatValue(row.doctor)}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">医生诊断：</span>${this.formatValue(row.doctorDiagnosis)}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">医生方案：</span>${this.formatValue(row.doctorPlan)}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">方案总额：</span>${this.formatValue(row.doctorTotalExpenses)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗费用：</span>${this.formatValue(row.doctorTreatmentExpenses)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">复诊次数：</span>${this.formatValue(row.reviewNum)}</span></div>
      <div style="width: 100%;height: 1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">知情同意书：</span>${this.formatValue(row.informedConsent)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">确费状态：</span>${this.formatValue(row.confirmExpense == '1' ? '已确费' : '未确费')}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗次数：</span>${this.formatValue(row.treatmentTimes)}</span><span style="margin-right:10px;"><span style="font-weight:bold;">温馨提示：</span>${this.formatValue(row.tipsTimes)}</span></div>`
    },
    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },
    formatValue(value) {
      if (value == null) {
        return ''
      } else {
        return value
      }
    },
    async getSFZToSearch() {
      const res = await startReadCard()
      if (res.result == 3) {
        this.$message.warning('请把身份证放到读卡器上')
        // this.$refs.saveTagInput.blur();
      } else if (res.result == 2) {
        // this.$message.warning('设备不存在')
      } else {
        this.queryParams.idNum = res.gmsfhm
      }

    },
    getClassifyList() {
      listClassify({ pageNum: 1, pageSize: 9999 }).then((response) => {
        this.classifyList = response.rows;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.waitDiagnosisBtn = false
      this.haveDiagnosisBtn = false
      this.haveDiagnosisBtnInfo = false
      this.getPatientList();
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.isDisabled) {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          createBy: this.userName,
          status: '',
          deptId: '',
          patientName: '',
          visitNum: '',
          idNum: '',
        };
      } else {
        this.resetForm("queryParams");
      }
      this.handleQuery();
    },
    // 获取地区
    getAddressData() {
      addressJson().then((res) => {
        this.areaList = res.data;
      });
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId")[0].children;
        if (this.deptOptions.length == 1) {
          this.baseInfo.deptId = this.deptOptions[0].deptId
        }
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    // 获取下拉搜索医生
    // getDoctorList() {
    //   listUser({
    //     pageNum: 1,
    //     pageSize: 9999,
    //     status: '0',
    //     roleId: 101,
    //   }).then(
    //     (response) => {
    //       if (response.recognizeCode == 200) {
    //         this.doctorList = response.rows
    //       }
    //     }
    //   )
    // },
    getSplit(str) {
      return str.split(',')
    },
    // 获取下拉搜索医生
    getDoctorList() {
      getListUser({ funcRole: '2', hospitalId: this.queryParams.hospitalId, deptId: this.queryParams.deptId }).then((response) => {
        if (response.code == 200) {
          this.doctorList = response.data
          // if (this.getSplit(this.dept.ancestors).length == 3) {//3级用户
          //   this.isDisabled = true
          // }
          // if (this.doctorList.length > 0) {
          //   let a = this.doctorList.some(item => {
          //     return item.userName == this.userName
          //   })
          //   if (a) {
          //     this.queryParams.createBy = this.userName
          //   }
          // }
        }
      });
    },
    //获取我已诊断顾客列表
    getDiagnosisDetailListInfo() {
      let Mdata = {}
      if (this.myDiagnosisDateRange) {
        Mdata = { beginTime: this.myDiagnosisDateRange[0] + ' ' + '00:00:00', endTime: this.myDiagnosisDateRange[1] + ' ' + '23:59:59', ...this.queryParams }
      } else {
        Mdata = { ...this.queryParams }
      }
      this.loading = true
      diagnosisDetailInfo(Mdata).then(
        (response) => {
          // console.log('getDiagnosisDetailList', response)
          this.patientList = response.rows;
          this.patientList.forEach(item => {
            if (item.consultationDiagnosis.includes(';')) {
              let Mobject = ''
              item.consultationDiagnosis.split(';').forEach(it => {
                Mobject += it + '<br>'
              })
              item.consultationDiagnosisValue = Mobject
            } else {
              item.consultationDiagnosisValue = item.consultationDiagnosis
            }
            if (item.doctorDiagnosis.includes(';')) {
              let MobjectDoctor = ''
              item.doctorDiagnosis.split(';').forEach(it => {
                MobjectDoctor += it + '<br>'
              })
              item.doctorDiagnosisValue = MobjectDoctor
            } else {
              item.doctorDiagnosisValue = item.doctorDiagnosis
            }
            if (item.doctorPlan != null) {
              if (item.doctorPlan.includes(';')) {
                let MobjectText = ''
                item.doctorPlan.split(';').forEach(it => {
                  MobjectText += it + '<br>'
                })
                item.doctorPlanValue = MobjectText
              } else {
                item.doctorPlanValue = item.doctorPlan
              }
            }

          });
          this.total = response.total;
          this.loading = false;
        }
      )
    },

    //获取我的录入顾客列表
    getDiagnosisDetailList() {
      let Mdata = {}
      if (this.myDiagnosisDateRange) {
        Mdata = { beginTime: this.myDiagnosisDateRange[0] + ' ' + '00:00:00', endTime: this.myDiagnosisDateRange[1] + ' ' + '23:59:59', ...this.queryParams }
      } else {
        Mdata = { ...this.queryParams }
      }
      this.loading = true
      diagnosisDetail(Mdata).then(
        (response) => {
          // console.log('getDiagnosisDetailList', response)
          this.patientList = response.rows;
          this.patientList.forEach(item => {
            if (item.consultationDiagnosis.includes(';')) {
              let Mobject = ''
              item.consultationDiagnosis.split(';').forEach(it => {
                Mobject += it + '<br>'
              })
              item.consultationDiagnosisValue = Mobject
            } else {
              item.consultationDiagnosisValue = item.consultationDiagnosis
            }
            if (item.doctorDiagnosis.includes(';')) {
              let MobjectDoctor = ''
              item.doctorDiagnosis.split(';').forEach(it => {
                MobjectDoctor += it + '<br>'
              })
              item.doctorDiagnosisValue = MobjectDoctor
            } else {
              item.doctorDiagnosisValue = item.doctorDiagnosis
            }
            if (item.doctorPlan != null) {
              if (item.doctorPlan.includes(';')) {
                let MobjectText = ''
                item.doctorPlan.split(';').forEach(it => {
                  MobjectText += it + '<br>'
                })
                item.doctorPlanValue = MobjectText
              } else {
                item.doctorPlanValue = item.doctorPlan
              }
            }

          });
          this.total = response.total;
          this.loading = false;
        }
      )
    },
    // 获取待诊断列表
    getWaitDiagnosisList() {
      this.loading = true
      diagnosisWait({
        pageNum: this.queryParams.pageNum, pageSize: this.queryParams.pageSize, hospitalId: this.queryParams.hospitalId,
        deptId: this.queryParams.deptId
      }).then(
        (response) => {
          // console.log('waitDiagnosis', response)
          this.patientList = response.rows;
          this.patientList.forEach(item => {
            if (item.consultationDiagnosis.includes(';')) {
              let Mobject = ''
              item.consultationDiagnosis.split(';').forEach(it => {
                Mobject += it + '<br>'
              })
              item.consultationDiagnosisValue = Mobject
            } else {
              item.consultationDiagnosisValue = item.consultationDiagnosis
            }
            if (item.doctorDiagnosis.includes(';')) {
              let MobjectDoctor = ''
              item.doctorDiagnosis.split(';').forEach(it => {
                MobjectDoctor += it + '<br>'
              })
              item.doctorDiagnosisValue = MobjectDoctor
            } else {
              item.doctorDiagnosisValue = item.doctorDiagnosis
            }
            if (item.doctorPlan != null) {
              if (item.doctorPlan.includes(';')) {
                let MobjectText = ''
                item.doctorPlan.split(';').forEach(it => {
                  MobjectText += it + '<br>'
                })
                item.doctorPlanValue = MobjectText
              } else {
                item.doctorPlanValue = item.doctorPlan
              }
            }
          });
          this.total = response.total;
          this.loading = false;
        }
      )
    },
    // 获取顾客登记列表
    getPatientList() {
      this.loading = true
      getList(this.queryParams).then(
        (response) => {
          this.patientList = response.rows;
          this.patientList.forEach(item => {
            if (item.consultationDiagnosis.includes(';')) {
              let Mobject = ''
              item.consultationDiagnosis.split(';').forEach(it => {
                Mobject += it + '<br>'
              })
              item.consultationDiagnosisValue = Mobject
            } else {
              item.consultationDiagnosisValue = item.consultationDiagnosis
            }
            if (item.doctorDiagnosis.includes(';')) {
              let MobjectDoctor = ''
              item.doctorDiagnosis.split(';').forEach(it => {
                MobjectDoctor += it + '<br>'
              })
              item.doctorDiagnosisValue = MobjectDoctor
            } else {
              item.doctorDiagnosisValue = item.doctorDiagnosis
            }
            if (item.doctorPlan != null) {
              if (item.doctorPlan.includes(';')) {
                let MobjectText = ''
                item.doctorPlan.split(';').forEach(it => {
                  MobjectText += it + '<br>'
                })
                item.doctorPlanValue = MobjectText
              } else {
                item.doctorPlanValue = item.doctorPlan
              }
            }
          });
          this.total = response.total;
          this.loading = false;
        }
      )
    },
    // 待诊断
    waitDiagnosis() {
      this.queryParams.pageNum = 1
      this.queryParams.createBy = ""
      this.waitDiagnosisBtn = true
      this.haveDiagnosisBtn = false
      this.haveDiagnosisBtnInfo = false
      this.getWaitDiagnosisList()
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)
    },

    // 我录入的
    haveDiagnosis() {
      this.queryParams.pageNum = 1
      this.queryParams.createBy = ""
      this.waitDiagnosisBtn = false
      this.haveDiagnosisBtn = true
      this.haveDiagnosisBtnInfo = false
      this.myDiagnosisDateRange = this.defaultTime
      this.getDiagnosisDetailList()
      this.getMyDiagnosisList(false)
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)
    },
    getMyDiagnosisList(value) {
      if (value) {
        this.statisticalDialogVisible = true
      } else {
        this.statisticalDialogVisible = false
      }

      this.statisticalTitle = '汇总统计'
      let Mdata = {}
      if (this.myDiagnosisDateRange) {
        Mdata = { beginTime: this.myDiagnosisDateRange[0] + ' ' + '00:00:00', endTime: this.myDiagnosisDateRange[1] + ' ' + '23:59:59', ...this.myDiagnosisQueryParams }
      } else {
        Mdata = { ...this.myDiagnosisQueryParams }
      }
      // let Mdata = { beginTime: this.myConsultationDateRange[0] + ' ' + '00:00:00',  endTime: this.myConsultationDateRange[1] + ' ' + '23:59:59' }
      myDiagnosis(Mdata).then((res) => {
        this.myDiagnosisTabList = res.rows
        this.myDiagnosisTabTotal = res.total
        if (this.myDiagnosisDateRange) {
          this.statisticalBeginTime = this.myDiagnosisDateRange[0]
          this.statisticalEndTime = this.myDiagnosisDateRange[1]
        } else {
          this.statisticalBeginTime = '诊断'
          this.statisticalEndTime = '至今'
        }
        if (res.rows.length > 0) {
          // this.statisticalBeginTime=res.rows.slice(-1)[0].consultationDate
          // this.statisticalEndTime=res.rows[0].consultationDate
          this.statisticalTotalExpenses = res.rows.reduce((cur, item) => {
            return cur + item.doctorTotalExpenses
          }, 0)
          this.statisticalTreatmentExpenses = res.rows.reduce((cur, item) => {
            return cur + item.doctorTreatmentExpenses
          }, 0)
          this.statisticalCount = res.rows.reduce((cur, item) => {
            return cur + Number(item.coun)
          }, 0)
        } else {
          this.statisticalTotalExpenses = '0'
          this.statisticalTreatmentExpenses = '0'
          this.statisticalCount = '0'
        }
      })
    },
    // 我录入的
    haveDiagnosisInfo() {
      this.queryParams.pageNum = 1
      this.queryParams.createBy = ""
      this.waitDiagnosisBtn = false
      this.haveDiagnosisBtn = false
      this.haveDiagnosisBtnInfo = true
      this.myDiagnosisDateRange = this.defaultTime
      this.getDiagnosisDetailListInfo()
      this.getMyDiagnosisListInfo(false)
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)
    },
    getMyDiagnosisListInfo(value) {
      if (value) {
        this.statisticalDialogVisible = true
      } else {
        this.statisticalDialogVisible = false
      }

      this.statisticalTitle = '汇总统计'
      let Mdata = {}
      if (this.myDiagnosisDateRange) {
        Mdata = { beginTime: this.myDiagnosisDateRange[0] + ' ' + '00:00:00', endTime: this.myDiagnosisDateRange[1] + ' ' + '23:59:59', ...this.myDiagnosisQueryParams }
      } else {
        Mdata = { ...this.myDiagnosisQueryParams }
      }
      // let Mdata = { beginTime: this.myConsultationDateRange[0] + ' ' + '00:00:00',  endTime: this.myConsultationDateRange[1] + ' ' + '23:59:59' }
      myDiagnosisInfo(Mdata).then((res) => {
        this.myDiagnosisTabList = res.rows
        this.myDiagnosisTabTotal = res.total
        if (this.myDiagnosisDateRange) {
          this.statisticalBeginTime = this.myDiagnosisDateRange[0]
          this.statisticalEndTime = this.myDiagnosisDateRange[1]
        } else {
          this.statisticalBeginTime = '诊断'
          this.statisticalEndTime = '至今'
        }
        if (res.rows.length > 0) {
          // this.statisticalBeginTime=res.rows.slice(-1)[0].consultationDate
          // this.statisticalEndTime=res.rows[0].consultationDate
          this.statisticalTotalExpenses = res.rows.reduce((cur, item) => {
            return cur + item.doctorTotalExpenses
          }, 0)
          this.statisticalTreatmentExpenses = res.rows.reduce((cur, item) => {
            return cur + item.doctorTreatmentExpenses
          }, 0)
          this.statisticalCount = res.rows.reduce((cur, item) => {
            return cur + Number(item.coun)
          }, 0)
        } else {
          this.statisticalTotalExpenses = '0'
          this.statisticalTreatmentExpenses = '0'
          this.statisticalCount = '0'
        }



      })
    },
    myDiagnosisTabSearchInfo() {
      this.getDiagnosisDetailListInfo()
      this.getMyDiagnosisListInfo(false)
    },

    myDiagnosisTabSearch() {
      this.getDiagnosisDetailList()
      this.getMyDiagnosisList(false)
    },
    closefullScreen() {
      this.$refs.Screenfull.closed()
    },
    closeCenterDialogVisible() {
      this.centerDialogVisible = false

      if (this.waitDiagnosisBtn) {
        this.getWaitDiagnosisList()
      } else if (this.haveDiagnosisBtn) {
        this.getDiagnosisDetailList()
      } else if (this.haveDiagnosisBtnInfo) {
        this.getDiagnosisDetailListInfo()
      } else {
        this.getPatientList()
      }
    },

    /** 修改诊前问卷按钮操作 */
    updateQuestionnaire(row) {
      this.formpreviewContList = null;
      this.formInfo = row;
      this.selectData.formId = null;
      this.questionnaireTitle = "修改顾客专病诊前问卷";
      this.questionnaireDialog = true;
      this.dialogNewAddBtnStatus = false;
      diseaseQuestionnaireList(this.formInfo.visitId).then((response) => {
        this.myAnswer = response.data;
        console.log("点击修改按钮获取的答案和表单列表", this.myAnswer);
        this.formList = this.myAnswer
        this.selectData.formId = response.data[0].formId
        // let newArr = [];
        // this.formList.forEach((item) => {
        //   this.myAnswer.forEach((it) => {
        //     if (item.formId == it.formId) {
        //       newArr.push(item);
        //     }
        //   });
        // });
        // this.formList = newArr;
        this.getFormContByFormId(this.myAnswer[0].formId);
      });
    },
    /** 修改诊前问卷按钮操作 */
    async updateFormAnswer(row) {
      this.$nextTick(() => {
        this.$refs.formPreview.$refs.listForm.validate((valid) => {
          if (valid) {
            let answerArr = [];
            const Vmodel = this.$refs.formPreview.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            this.formpreviewContList.forEach((item, index) => {
              this.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            console.log(this.formInfo);
            let mData = {
              visitLogId: this.formInfo.visitLogId,
              answer: answerStr,
            };
            updateAnswer(1, mData).then((response) => {
              this.$message.success("修改成功");
              this.questionnaireDialog = false;
            });
          }
        });
      });
    },
    async addQuestionForm() {
      this.selectData.diseaseId = null
      this.selectData.formId = null;
      this.formpreviewContList = null;
      this.dialogNewAddBtnStatus = true;
      this.formList = [],
        this.questionnaireTitle = "新增顾客专病诊前问卷";
      // listForm(
      //   this.addDateRange({
      //     pageNum: 1,
      //     formType: 1,
      //     pageSize: 999,
      //   })
      // ).then((response) => {
      //   this.formList = response.rows;
      //   this.selectData.formId = null;
      //   this.formpreviewContList = null;
      //   this.dialogNewAddBtnStatus = true;
      //   this.questionnaireTitle = "新增顾客专病诊前问卷";
      //   let newArr = [];
      //   for (let i = 0; i < this.formList.length; i++) {
      //     if (
      //       !this.myAnswer.find(
      //         (item) => item.formId == this.formList[i].formId
      //       )
      //     ) {
      //       newArr.push(this.formList[i]);
      //     }
      //   }
      //   this.formList = newArr;
      //   console.log("新加问卷后的formlist", this.formList);
      // });
    },
    // 专病问卷
    openQuestionnaire(row) {
      this.formInfo = row;
      this.selectData.diseaseId = null
      this.selectData.formId = null;
      this.formpreviewContList = null;
      this.questionnaireDialog = true;
      this.dialogNewAddBtnStatus = true;
      this.questionnaireTitle = "新增顾客专病诊前问卷";
    },
    //提交答案
    submitAnswer() {
      const that = this
      that.$nextTick(() => {
        that.$refs.formPreview.$refs.listForm.validate((valid) => {
          console.log(that.$refs.formPreview.$refs.listForm);
          if (valid) {
            let answerArr = [];
            const Vmodel = that.$refs.formPreview.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            that.formpreviewContList.forEach((item, index) => {
              that.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            let mData = {
              visitId: that.formInfo.visitId,
              patientId: that.formInfo.patientId,
              formId: that.formInfo.formId,
              answer: answerStr,
              formType: '1', //专病表单
            };
            addFormAnswer(1, mData).then((response) => {
              that.$message.success('提交成功')
              that.questionnaireDialog = false
              if (this.waitDiagnosisBtn) {
                this.getWaitDiagnosisList()
              } else if (this.haveDiagnosisBtn) {
                this.getDiagnosisDetailList()
              } else if (this.haveDiagnosisBtnInfo) {
                this.getDiagnosisDetailListInfo()
              } else {
                this.getPatientList()
              }
            });
          }
        });
      });
    },

    // 通过formid获取form内容
    getFormContByFormId(current) {
      if (current == "") {
        return;
      }

      listFormCont({
        formId: current,
      }).then((response) => {
        this.questionFormInfo.name = response.name;
        this.questionFormInfo.remark = response.remark;
        this.formpreviewContList = response.rows;
        let mAnswer = null;
        if (this.dialogNewAddBtnStatus === false) {
          this.myAnswer.forEach((it) => {
            if (it.formId === current) {
              mAnswer = JSON.parse(it.answer);
              this.formInfo.visitLogId = it.visitLogId;
            }
          });
        }
        this.formpreviewContList.forEach((item, index) => {
          if (this.dialogNewAddBtnStatus === false) {
            this.$set(item, "answer", mAnswer[index].answer);
          } else {
            if (item.questionType == "2") {
              this.$set(item, "answer", []);
            } else {
              this.$set(item, "answer", null);
            }
          }
        });
      });
      this.formInfo.formId = current;
      console.log(this.formList);
    },
    /** 查询表单列表 */
    getFormList(diseaseId) {
      this.selectData.formId = null;
      // let hospitalId
      // if (this.hospital.ancestors == '0') {
      //   hospitalId = ''
      // } else {
      //   hospitalId = this.hospital.deptId
      // }
      listFormDept(
        this.addDateRange({
          pageNum: 1,
          formType: "1",
          diseaseId: diseaseId,
          pageSize: 9999,
          deptId: this.formInfo.deptId,
          status: '0',
        })
      ).then((response) => {
        this.formList = response.rows;
        let newArr = [];
        //新增时过滤已经新增的  修改时只有已修改的
        if (this.dialogNewAddBtnStatus) {
          for (let i = 0; i < this.formList.length; i++) {
            if (
              !this.myAnswer.find(
                (item) => item.formId == this.formList[i].formId
              )
            ) {
              newArr.push(this.formList[i]);
            }
          }
        }
        this.formList = newArr;
      });
    },




    // 新增方案
    newAdd(row) {
      this.baseInfo = row
      this.baseInfo.updateStatus = false
      this.baseInfo.referenceStatus = false
      this.planTitle = '新增方案'
      this.centerDialogVisible = true
      this.$refs.Screenfull.open()
    },
    updatePlan(row) {
      this.baseInfo = row
      this.baseInfo.updateStatus = true
      this.baseInfo.referenceStatus = false
      this.planTitle = '修改方案'
      this.centerDialogVisible = true
      this.$refs.Screenfull.open()
    },
    referencePlan(row) {
      if (row.visitPlanId) {
        this.baseInfo = row
        this.baseInfo.updateStatus = false
        this.baseInfo.referenceStatus = true
        this.planTitle = '引用咨询方案'
        this.centerDialogVisible = true
        this.$refs.Screenfull.open()
      } else {
        this.$confirm('该顾客没有咨询方案！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            // console.log(content)
          })
          .catch((error) => {
            // console.log(error)
          })

      }
    },
    goDetail(row) {
      this.detailTitle = '顾客详情'
      this.baseInfo = row
      this.detailDialogVisible = true

    },




    /** 通用问卷start */

    /** 打开通用问卷按钮操作 */
    async openQuestionnaireUniversal(row) {
      this.formInfoUniversal = row;
      // let hospitalId
      // if (this.hospital.ancestors == '0') {
      //   hospitalId = ''
      // } else {
      //   hospitalId = this.hospital.deptId
      // }
      currencyFormId({ deptId: row.deptId }).then((res) => {
        this.formInfoUniversal.formId = res.data;
        if (res.data) {
          this.getFormContList();
        }
        this.dialogNewAddBtnStatusUniversal = true;
        this.questionnaireTitleUniversal = "新增顾客通用诊前问卷";
      });
    },
    /** 查询表单内容控件列表 */
    getFormContList() {
      listFormCont({
        formId: this.formInfoUniversal.formId,
      }).then((response) => {
        this.questionFormInfoUniversal.name = response.name;
        this.questionFormInfoUniversal.remark = response.remark;
        this.formpreviewContListUniversal = response.rows;
        this.formpreviewContListUniversal.forEach((item, index) => {
          if (this.dialogNewAddBtnStatusUniversal === false) {
            this.$set(item, "answer", this.myAnswerUniversal[index].answer);
          } else {
            if (item.questionType === "2") {
              this.$set(item, "answer", []);
            } else {
              this.$set(item, "answer", null);
            }
          }
        });
      });
      this.questionnaireDialogUniversal = true;
    },
    /** 修改通用问卷打开按钮操作 */
    updateQuestionnaireUniversal(row) {
      this.dialogNewAddBtnStatusUniversal = false;
      getQuestionnaireCommon(row.visitId).then((response) => {
        const visitLogId = response.data[0].visitLogId;
        console.log("点击修改按钮获取的答案和表单列表", this.myAnswerUniversal);
        detailFormAndAnswer(visitLogId).then((response) => {
          this.formInfoUniversal = response.data;
          this.myAnswerUniversal = JSON.parse(response.data.answer);
          this.getFormContList();
        });
      });
      this.questionnaireTitleUniversal = "修改顾客通用诊前问卷";

    },
    /** 修改通用问卷答案提交按钮操作 */
    async updateFormAnswerUniversal(row) {
      this.$nextTick(() => {
        this.$refs.formPreviewUniversal.$refs.listForm.validate((valid) => {
          if (valid) {
            let answerArr = [];
            const Vmodel = this.$refs.formPreviewUniversal.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            this.formpreviewContListUniversal.forEach((item, index) => {
              this.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            let mData = {
              visitLogId: this.formInfoUniversal.visitLogId,
              answer: answerStr,
            };
            updateAnswer(1, mData).then((response) => {
              this.$message.success("修改成功");
              this.questionnaireDialogUniversal = false;
            });
          }
        });
      });
    },
    /** 提交通用问卷答案按钮操作 */
    submitAnswerUniversal() {
      let that = this
      this.$nextTick(() => {
        this.$refs.formPreviewUniversal.$refs.listForm.validate((valid) => {
          if (valid) {
            let answerArr = [];
            const Vmodel = this.$refs.formPreviewUniversal.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            this.formpreviewContListUniversal.forEach((item, index) => {
              this.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            let mData = {
              visitId: this.formInfoUniversal.visitId,
              patientId: this.formInfoUniversal.patientId,
              formId: this.formInfoUniversal.formId,
              answer: answerStr,
              formType: '0', //通用表单
            };
            addFormAnswer(1, mData).then((response) => {
              that.$message.success("提交成功");
              that.questionnaireDialogUniversal = false;
              if (this.waitDiagnosisBtn) {
                this.getWaitDiagnosisList()
              } else if (this.haveDiagnosisBtn) {
                this.getDiagnosisDetailList()
              } else if (this.haveDiagnosisBtnInfo) {
                this.getDiagnosisDetailListInfo()
              } else {
                this.getPatientList()
              }
            });
          }
        });
      });
    },

    /** 通用问卷end */

  },
};
</script>
<style scoped rel="stylesheet/scss"  lang="scss">
/*::v-deep .el-dialog .el-dialog__close {*/
/*  color: red;*/
/*  font-size: 28px;*/
/*  font-weight: 700;*/
/*}*/

.base-info-box {
  line-height: 50px;
}

.base-info-box span {
  margin-right: 15px;
}

::v-deep .el-dialog {
  margin-top: 0 !important;
}

.min-height {
  min-height: 700px;
}</style>
